<template>
  <div class="course-detail-container">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <h1>{{ courseInfo.name }}</h1>
      </template>
    </el-page-header>
    
    <div v-loading="loading" class="course-content">
      <el-row :gutter="20">
        <!-- 课程封面 -->
        <el-col :span="8">
          <el-card shadow="hover">
            <img :src="courseInfo.couPic || defaultCourseImage" class="cover-image">
          </el-card>
        </el-col>
        
        <!-- 课程信息 -->
        <el-col :span="16">
          <el-card shadow="never">
            <h2>课程简介</h2>
            <p>{{ courseInfo.introduction }}</p>
            
            <div class="course-meta">
              <el-tag type="success" v-if="courseInfo.price === 0">免费课程</el-tag>
              <el-tag type="danger" v-else>¥{{ courseInfo.price }}</el-tag>
              
              <div class="stats">
                <span><el-icon><Star /></el-icon> {{ courseInfo.likeCount || 0 }}人点赞</span>
                <span><el-icon><Collection /></el-icon> {{ courseInfo.collectionCount || 0 }}人收藏</span>
                <span><el-icon><Share /></el-icon> {{ courseInfo.shareCount || 0 }}次分享</span>
                <span><el-icon><View /></el-icon> {{ courseInfo.clicks || 0 }}次学习</span>
              </div>
            </div>
            
            <div class="action-buttons">
              <el-button-group class="extra-actions">
                <el-button :icon="Star" @click="handleLike">点赞</el-button>
                <el-button :icon="Collection" @click="handleCollect">收藏</el-button>
                <el-button :icon="Share" @click="handleShare">分享</el-button>
              </el-button-group>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 课程章节内容 -->
      <div class="course-chapters">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>课程章节</span>
            </div>
          </template>
          
          <el-collapse v-model="activeChapter">
            <el-collapse-item 
              v-for="chapter in courseInfo.chapters" 
              :key="chapter.id"
              :name="chapter.id"
            >
              <template #title>
                <div class="chapter-title">
                  <span class="chapter-index">第{{ chapter.index }}章</span>
                  <span class="chapter-name">{{ chapter.title }}</span>
                </div>
              </template>
              <div class="chapter-content">
                <el-button 
                  type="text" 
                  @click="playVideo(chapter)"
                >
                  <el-icon><VideoPlay /></el-icon> 播放视频
                </el-button>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>
      
      <!-- 课程评价 -->
      <div class="course-reviews">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>课程评价</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="showReviewDialog"
                v-if="!hasReviewed"
              >
                发表评价
              </el-button>
            </div>
          </template>
          
          <!-- 添加评论区域 -->
          <div class="add-review" v-if="!hasReviewed">
            <el-input
              v-model="newReview.content"
              type="textarea"
              :rows="3"
              placeholder="写下您的课程评价..."
              maxlength="300"
              show-word-limit
            />
            <div class="review-actions">
              <el-rate v-model="newReview.score" />
              <el-button 
                type="primary" 
                size="small" 
                @click="submitReview"
                :loading="reviewLoading"
              >
                提交评价
              </el-button>
            </div>
          </div>
          
          <!-- 评价列表 -->
          <div v-if="courseInfo.appraises?.length > 0">
            <div 
              v-for="review in courseInfo.appraises" 
              :key="review.id" 
              class="review-item"
            >
              <div class="review-header">
                <el-avatar :size="40" :src="getAvatar(review.studentId)" />
                <div class="review-info">
                  <span class="review-author">学生{{ review.studentId }}</span>
                  <el-rate 
                    v-model="review.score" 
                    disabled 
                    show-score 
                    score-template="{value}分" 
                  />
                </div>
                <span class="review-time">{{ formatTime(review.createTime) }}</span>
              </div>
              <div class="review-content">
                {{ review.content }}
              </div>
            </div>
          </div>
          <el-empty description="暂无评价" v-else />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  ElMessage, 
  ElPageHeader, 
  ElCard, 
  ElTag, 
  ElButton, 
  ElCollapse, 
  ElCollapseItem, 
  ElRate, 
  ElEmpty,
  ElInput
} from 'element-plus'
import {
  Star,
  Collection,
  Share,
  View,
  VideoPlay
} from '@element-plus/icons-vue'
import axios from '@/utils/request'
import defaultCourseImage from '@/assets/fault.png'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)
const activeChapter = ref([])
const reviewLoading = ref(false)

// 课程信息
const courseInfo = ref({
  name: '',
  introduction: '',
  couPic: '',
  price: 0,
  chapters: [],
  appraises: []
})

// 新评论
const newReview = ref({
  score: 5,
  content: ''
})

// 检查是否已评价
const hasReviewed = computed(() => {
  if (!authStore.userId) return false
  return courseInfo.value.appraises?.some(
    review => review.studentId === authStore.userId
  )
})

// 获取课程详情
const fetchCourseDetail = async () => {
  try {
    loading.value = true
    const courseId = route.params.id
    
    const response = await fetch(`http://localhost:8082/api/course-detail/${courseId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    
    courseInfo.value = {
      ...data,
      couPic: data.couPic || defaultCourseImage,
      chapters: data.chapters || [],
      appraises: data.appraises || [],
      likeCount: data.likeCount || 0,
      collectionCount: data.collectionCount || 0,
      shareCount: data.shareCount || 0,
      clicks: data.clicks || 0
    }
    
  } catch (error) {
    console.error('获取课程失败:', error)
    ElMessage.error('获取课程详情失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  const from = route.query.from || '/'
  router.push(from)
}

// 播放视频
const playVideo = (chapter) => {
  if (!chapter.url) {
    ElMessage.warning('该章节没有视频内容')
    return
  }
  
  router.push({
    path: '/video-player',
    query: {
      courseId: courseInfo.value.id,
      chapterId: chapter.id,
      videoUrl: chapter.url
    }
  })
}

// 提交评价
const submitReview = async () => {
  if (!newReview.value.content.trim()) {
    ElMessage.warning('请填写评价内容')
    return
  }

  try {
    reviewLoading.value = true
    
    const response = await axios.post(`/api/course-detail/${courseInfo.value.id}/review`, {
      userId: authStore.userId,
      score: newReview.value.score,
      content: newReview.value.content
    })
    
    if (response.data) {
      ElMessage.success({
        message: '评价提交成功，感谢您对本课程的评价！',
        duration: 3000
      })
      
      newReview.value = { score: 5, content: '' }
      
      const newAppraise = {
        id: Date.now(),
        studentId: authStore.userId,
        score: response.data.score || newReview.value.score,
        content: response.data.content || newReview.value.content,
        createTime: new Date().toISOString()
      }
      
      courseInfo.value.appraises = [newAppraise, ...courseInfo.value.appraises]
      
      setTimeout(() => {
        const reviewsSection = document.querySelector('.course-reviews')
        if (reviewsSection) {
          reviewsSection.scrollIntoView({ behavior: 'smooth' })
        }
      }, 100)
    }
  } catch (error) {
    ElMessage.error('评价提交失败: ' + (error.response?.data?.message || error.message))
    console.error('提交评价失败:', error)
  } finally {
    reviewLoading.value = false
  }
}

// 格式化时间
const formatTime = (time) => {
  return time ? new Date(time).toLocaleString() : '未知时间'
}

// 获取头像（模拟）
const getAvatar = (studentId) => {
  return `https://robohash.org/${studentId}?set=set4`
}

// 点赞、收藏、分享处理函数
const handleLike = async () => {
  try {
    await axios.post(`/api/course-detail/${courseInfo.value.id}/like`)
    courseInfo.value.likeCount++
    ElMessage.success('点赞成功')
  } catch (error) {
    ElMessage.error('点赞失败')
  }
}

const handleCollect = async () => {
  try {
    await axios.post(`/api/course-detail/${courseInfo.value.id}/collect`)
    courseInfo.value.collectionCount++
    ElMessage.success('收藏成功')
  } catch (error) {
    ElMessage.error('收藏失败')
  }
}

const handleShare = () => {
  courseInfo.value.shareCount++
  ElMessage.success('已生成分享链接')
}

const showReviewDialog = () => {
  // 可以在这里实现显示评价对话框的逻辑
}

onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
}

.cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.course-content {
  margin-top: 20px;
}

.course-meta {
  margin: 20px 0;
}

.stats {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
}

.stats span {
  display: flex;
  align-items: center;
  color: #666;
}

.stats .el-icon {
  margin-right: 5px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.extra-actions {
  margin-left: 15px;
}

.course-chapters,
.course-reviews {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
}

.chapter-title {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.chapter-index {
  margin-right: 10px;
  color: #409eff;
}

.chapter-content {
  padding: 0 20px;
  display: flex;
  align-items: center;
}

.add-review {
  margin-bottom: 20px;
}

.review-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.review-info {
  flex: 1;
  margin-left: 10px;
}

.review-author {
  font-weight: bold;
  margin-right: 10px;
}

.review-time {
  color: #999;
  font-size: 12px;
}

.review-content {
  padding-left: 50px;
  color: #333;
  line-height: 1.6;
}
</style>